<?php

namespace App\Jobs;

use App\Exports\BookCatalog8;
use App\Models\DownloadJobQueue;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SlowExeCatalog8 implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $data;
    public $isRun;
    public $downloadJobId;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($downloadJobId)
    {
        $this->downloadJobId = $downloadJobId;
        $info = DownloadJobQueue::query()
            ->where('download_job_id', $downloadJobId)
            ->where('status', 0)
            ->orderBy('id')
            ->first();

        $this->isRun = 0;
        if ($info) { //如果有数据就执行
            $this->isRun = 1;
            $this->data  = $info->toArray();
            $info->update(['status' => 1]);
        }
    }

    /**
     * Execute the job.
     * 把导出卷内文件进行削峰，比如我一次性导出 100个案卷，按照设定的每三个案卷分成一组，一共会分成 34 个导出，原来foreach循环34次添加到任务，这34次就相当于一个瞬间高并发
     * 然后我就把34次，先执行一个，剩余的33次foreach添加到SlowExeExport 任务，
     * @return void
     */
    public function handle()
    {
        if ($this->isRun) {
            $data = $this->data;
            $fileInfo = explode(".",basename($data['file_name']));
            if($data['part_company_id'] && $data['project_classify_id']) {
                (new BookCatalog8($data['part_company_id'], $data['project_classify_id'], $data['book_title_ids'], $fileInfo[0]))->store('public/' . $data['file_name'])->chain([
                    new SlowExeCatalog8($this->downloadJobId)
                ]);
            }
        }
    }
}
